import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.metrics import accuracy_score

if __name__ == '__main__':
    # 加载 digits 数据集
    digits = load_digits()
    features = digits.data
    labels = digits.target
    # 使用 KMeans 算法进行聚类
    kmeans = KMeans(n_clusters=10, random_state=42)
    kmeans.fit(features)
    cluster_labels = kmeans.labels_
    # 使用 PCA 进行数据降维
    pca = PCA(n_components=2)
    features_pca = pca.fit_transform(features)
    # 可视化原始数据和聚类结果
    plt.figure(figsize=(14, 8))

    plt.subplot(1, 2, 1)
    plt.scatter(features_pca[:, 0], features_pca[:, 1], c=labels, cmap='tab10', edgecolor='k', s=50)
    plt.title('Original Data (PCA)')
    plt.xlabel('PCA Component 1')
    plt.ylabel('PCA Component 2')

    plt.subplot(1, 2, 2)
    plt.scatter(features_pca[:, 0], features_pca[:, 1], c=cluster_labels, cmap='tab20', edgecolor='k', s=50)
    plt.title('KMeans Clustering (PCA)')
    plt.xlabel('PCA Component 1')
    plt.ylabel('PCA Component 2')

    plt.tight_layout()
    plt.show()

    # 计算分类精度
    cluster_to_label = {}
    for cluster in np.unique(cluster_labels):
        cluster_indices = np.where(cluster_labels == cluster)[0]
        true_labels = labels[cluster_indices]
        most_common_label = np.bincount(true_labels).argmax()
        cluster_to_label[cluster] = most_common_label
    predicted_labels = [cluster_to_label[cluster] for cluster in cluster_labels]
    accuracy = accuracy_score(labels, predicted_labels)
    print("分类精度：", accuracy)
